package com.eonmind.vip.task;

import com.eonmind.common.contract.application.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Set;

@Component
public class DelSignRecordTask {

    @Autowired
    private RedisService redisService;

    // 每月第一天00:00:00执行任务
    @Scheduled(cron = "0 0 0 1 * ?")
    public void deleteLastUserSignRecordsInRedis() {
        System.out.println("--------------- 开始删除上个月的签到记录 -----------------");
        // 获取上个月的第一天和最后一天
        LocalDate lastMonthFirstDay = LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());

        // 格式化日期
        String lastYear = String.valueOf(lastMonthFirstDay.getYear());
        String lastMonth = String.valueOf(lastMonthFirstDay.getMonthValue());

        // 构建匹配上个月日期的键的模式
        String pattern = "sign:*:" + lastYear + ":" + lastMonth;

        // 建议使用 scan 命令
        Set<String> keys = redisService.scanKeys(pattern);
        if (keys != null) {
            redisService.deleteKeys(keys);
        }
        System.out.println("----------------- 删除成功 -----------------");
    }
}
